package example

import (
	"context"
	"fmt"
	"time"
)

func T4(){
	c := make(chan int)
	quit := make(chan int)

	go fib(c, quit)

	for i := 0; i < 10; i++ {
		fmt.Println(<-c)
	}
	//close(quit)
}

func fib(c,quit chan int){
	x,y := 0, 1
	for{
		select {
		case c<-x:
			x,y=y,y+x
		case <-quit:
			fmt.Println("quit")
			return
		}
	}
}

func T4_2(){
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	c := make(chan int)
	go fib2(ctx, c)
	for i := 0; i < 10; i++ {
		fmt.Println(<-c)
	}
	time.Sleep(time.Second*5)
}

func fib2(ctx context.Context, c chan int){
	x,y := 0,1
	for  {
		select {
		case c<-x:
			x,y=y,y+x
		case <-ctx.Done():
			fmt.Println("quit")
			return
		}
	}
}
